<template>
  <div class="container-box">

    <el-row :gutter="10">
      <el-col :xs="24" :sm="24" :md="10" :lg="10" :xl="10" style="margin-bottom: 10px">
        <div class="title-box">字典列表</div>
        <div class="table-wrap">
          <div class="filter-box">
            <el-form :inline="true" :model="query" class="demo-form-inline">
              <template v-for="(item, index) in columns.filter(d => d.isFilter)">
                <el-form-item :key="index" :label="item.title">
                  <el-input v-model="query[item.key]" :placeholder="`请输入${item.title}`" />
                </el-form-item>
              </template>
            </el-form>
            <el-row>
              <el-button type="primary" @click="handleRowOption('', 'addDict')">新增字典</el-button>
              <el-button type="primary" @click="getData">查询</el-button>
              <el-button type="primary" @click="handleRowOption('', 'refresh')">刷新</el-button>
            </el-row>
          </div>
          <div class="table-box">
            <el-table :data="list" border stripe header-row-class-name="table-header-row" @row-click="clickTableRow($event, 'dict')">
              <template v-for="(item, index) in columns.filter(d => d.isTable)">
                <el-table-column :key="index" :prop="item.key" :label="item.title" :sortable="item.sortable">
                  <template slot-scope="scope">
                    <div v-if="item.key === ''" class="">{{ scope.row[item.key] }}</div>
                    <div v-else class="">{{ handleRowResult(item, scope.row) }}</div>
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </div>
        </div>
      </el-col>
      <el-col v-if="selDict && selDict.id" :xs="24" :sm="24" :md="14" :lg="14" :xl="14">
        <div class="title-box">{{ selDict && selDict.remark ? selDict.remark : '' }} 字典详情</div>
        <div class="table-wrap">
          <div class="filter-box">
            <el-form :inline="true" :model="dictDetailQuery" class="demo-form-inline">
              <template v-for="(item, index) in dictDetailColums.filter(d => d.isFilter)">
                <el-form-item :key="index" :label="item.title">
                  <el-input v-model="query[item.key]" :placeholder="`请输入${item.title}`" />
                </el-form-item>
              </template>
            </el-form>
            <el-button type="primary" icon="el-icon-plus" @click="handleRowOption('', 'addDictDetail')">新增字典详情</el-button>
          </div>
          <div class="table-box">
            <el-table :data="dictDetailList" border stripe header-row-class-name="table-header-row">
              <template v-for="(item, index) in dictDetailColums.filter(d => d.isTable)">
                <el-table-column :key="index" :prop="item.key" :label="item.title" :sortable="item.sortable">
                  <template slot-scope="scope">
                    <div v-if="item.key === ''" class="">{{ scope.row[item.key] }}</div>
                    <div v-else class="">{{ handleRowResult(item, scope.row) }}</div>
                  </template>
                </el-table-column>
              </template>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <div class="but-box">
                    <el-button type="primary" icon="el-icon-edit" circle @click="handleRowOption(scope.row, 'editDictDetail')" />
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-dialog :title="`${dialogForm.id ? '编辑' : '新增'} ${dialogType==='addDict'?'字典':['addDictDetail', 'editDictDetail'].includes(dialogType)?'字典详情':''}`" :visible.sync="dialogVisible" :show-close="false" :close-on-click-modal="false" :destroy-on-close="true">
      <el-form ref="dialogForm" :model="dialogForm" :rules="dialogRules" label-width="100px">
        <template v-for="(column, index) in dialogColums.filter(d => d.isForm)">
          <el-form-item v-if="column.key === 'value'" :key="index" :label="column.title" :prop="column.key">
            <el-input v-model.trim="dialogForm[column.key]" :type="column.type" :placeholder="`请输入${column.title}`" :disabled="dialogType === 'editDictDetail'" />
          </el-form-item>
          <el-form-item v-else-if="column.key === 'cat_id'" :key="index" :label="column.title" :prop="column.key">
            <el-select v-model="dialogForm[column.key]" :placeholder="`请选择${column.title}`" style="width: 100%;">
              <el-option v-for="item in goodsCategory" :key="item.cat_id" :label="item.cat_name" :value="item.cat_id" />
            </el-select>
          </el-form-item>
          <el-form-item v-else :key="index" :label="column.title" :prop="column.key">
            <el-input v-if="column.type === 'number'" v-model.number="dialogForm[column.key]" :type="column.type" :placeholder="`请输入${column.title}`" />
            <el-input v-else v-model.trim="dialogForm[column.key]" :type="column.type" :placeholder="`请输入${column.title}`" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="saving" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="saving" @click="onDialogConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { systemDictDetail, systemDictAdd, systemDictDetailEdit } from '../../api/system'
export default {
  name: 'SystemDict',
  data() {
    // 字典名称唯一
    var dictNameValidator = (rule, value, callback) => {
      value = value.trim();
      if (!value) {
        callback(new Error(`请输入字典名称`));
      }
      else if (this.list.filter(d => d.name === value && d.id !== this.dialogForm?.id).length > 0) {
        callback(new Error(`字典名称 ${value} 已存在`));
      }
      else {
        callback();
      }
    };
    // 字典描述唯一
    var dictRemarkValidator = (rule, value, callback) => {
      value = value.trim();
      if (!value) {
        callback(new Error(`请输入字典名称`));
      }
      else if (this.list.filter(d => d.remark === value && d.id !== this.dialogForm?.id).length > 0) {
        callback(new Error(`字典名称 ${value} 已存在`));
      }
      else {
        callback();
      }
    };
    // 字典值唯一
    var dictDetailValueValidator = (rule, value, callback) => {
      value = value.trim();
      console.log('this.dictDetailList.filter(d => d.label === value).length==', this.dictDetailList.filter(d => d.value === value).length);
      if (!value) {
        callback(new Error(`请输入字典值`));
      }
      else if (this.dictDetailList.filter(d => d.value === value && d.id !== this.dialogForm?.id).length > 0) {
        callback(new Error(`字典值 ${value} 已存在`));
      }
      else {
        callback();
      }
    };
    // 字典标签唯一
    var dictDetailLabelValidator = (rule, value, callback) => {
      value = value.trim();
      console.log('this.dictDetailList.filter(d => d.label === value).length==', this.dictDetailList.filter(d => d.label === value && d.id !== this.dialogForm?.id).length);
      if (!value) {
        callback(new Error(`请输入字典标签`));
      }
      else if (this.dictDetailList.findIndex(d => d.label === value && d.id !== this.dialogForm?.id).length > 0) {
        callback(new Error(`字典标签 ${value} 已存在`));
      }
      else {
        callback();
      }
    };
    return {
      columns: [
        { title: '字典名称', key: 'remark', type: 'text', isFilter: true, isTable: true, isForm: true, tip: '可以使用中文' },
        { title: '字典值', key: 'name', type: 'text', isFilter: false, isTable: true, isForm: true, tip: '最好使用英语单词' }
      ],
      list: [],
      query: {},
      dictDetailColums: [
        { title: '字典标签', key: 'label', type: 'text', sortable: true, isFilter: false, isTable: true, isForm: true, tip: '可以使用中文' },
        { title: '字典值', key: 'value', type: 'text', sortable: true, isFilter: false, isTable: true, isForm: true, tip: '最好使用英语单词' },
        { title: '排序', key: 'sort', type: 'number', sortable: true, isFilter: false, isTable: true, isForm: true }
      ],
      selDict: { id: '' },
      dictDetailList: [],
      dictDetailQuery: {},
      dictDetailDialogVisible: false,
      dictDetailForm: {
        name: 'goods_attr',
        remark: '商品规格'
        // store_house_name: '',
        // store_id: '',
        // area_address: '',
      },
      dictDetailRules: {
        store_house_name: [{ required: true, message: '请输入仓库名称', trigger: ['change', 'blur'] }],
        store_id: [{ required: true, message: '请选择所属门店', trigger: ['change', 'blur'] }],
        area_address: [{ required: true, message: '请输入地址', trigger: ['change', 'blur'] }]
      },
      dict: {},

      saving: false,
      dialogType: '',
      dialogVisible: false,
      dialogColums: [],
      dialogRules: {
        name: [
          { required: true, message: '请输入字典名称', trigger: ['change', 'blur'] },
          { required: true, validator: dictNameValidator }
        ],
        remark: [
          { required: true, message: '请输入字典描述', trigger: ['change', 'blur'] },
          { required: true, validator: dictRemarkValidator }
        ],
        label: [
          { required: true, message: '请输入字典标签', trigger: ['change', 'blur'] },
          { required: true, validator: dictDetailLabelValidator }
        ],
        value: [
          { required: true, message: '请输入字典值', trigger: ['change', 'blur'] },
          { required: true, validator: dictDetailValueValidator }
        ],
        sort: [{ required: true, message: '请输入排序', trigger: ['change', 'blur'] }]
      },
      dialogForm: {
        goods_name: '捷时达995硅酮结构密封胶',
        full_goods_name: '捷时达995',
        cat_id: 77,
        sort: 500,
        unit_name: '支',
        unit_name2: '件',
        unit_convert: 1,
        unit_convert2: 20
      }
    };
  },
  computed: {
    dictDetails() {
      const dictDetails = this.$store.state.system.dictDetails;
      return dictDetails;
    },
    dictData() {
      const dictData = this.$store.getters.dictData;
      console.log('dictData==', dictData);
      this.list = dictData?.data || [];
      return dictData;
    }
  },
  watch: {
    // dictDetailDialogVisible(val, oldVal) {
    //   this.dictDetailForm = {}
    // }
    'selDict.id': {
      handler(val, oldVal) {
        console.log('selDict.id==', this.selDict.id, val, oldVal);
        if (val && val !== oldVal) {
          this.getDictDetail();
        }
      },
      deep: true
    }
  },
  created() {
    console.log('1--this.dictData==', this.dictData);
    this.getData();
    // this.getdictDetail();
  },
  methods: {
    async getData() {
      const { list } = await this.$store.dispatch('system/getDictList')
      // const { data } = await systemDict();
      this.list = list || [];
      // console.log('this.list==', this.list);
    },
    async getDictDetail() {
      if (!this.selDict?.id) return;
      const payload = { dict_id: this.selDict?.id }
      const { data } = await systemDictDetail(payload);
      this.dictDetailList = data?.list || [];
      this.$store.dispatch('system/updateDictDetail', { data: this.dictDetailList, name: this.selDict.name })
      console.log('this.dictDetailList==', this.dictDetailList);
    },
    clickTableRow(e, type) {
      console.log('clickTableRow==', e, type);
      if (type === 'dict') {
        this.selDict = { ...e };
      }
    },
    handleRowResult(item, row) {
      // console.log('handleRowResult--item', item, row);
      if (item.key === 'stock') {
        if (row.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
          const unitNum = row.stock % row.unit_convert2;
          const unitNum2 = Math.floor(row.stock / row.unit_convert2);
          return `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
        }
        return `${row.stock}${row.unit_name}`
      }
      if (item.key === 'store_id') {
        return this.dict.store[row[item.key]]?.store_name || row[item.key];
      }
      return row[item.key] || '';
    },
    async handleRowOption(row, type) {
      console.log('handleRowOption--row==', row, type);
      this.dialogType = type;
      if (type === 'addDict') {
        this.$nextTick(() => {
          this.dialogForm = {};
          this.dialogColums = this.$json.cloneDeep(this.columns)
        })
      }
      else if (type === 'addDictDetail') {
        this.$nextTick(() => {
          this.dialogForm = { sort: 500 };
          this.dialogColums = this.$json.cloneDeep(this.dictDetailColums)
        })
      }
      else if (type === 'editDictDetail') {
        this.$nextTick(() => {
          this.dialogForm = this.$json.cloneDeep(row);
          this.dialogColums = this.$json.cloneDeep(this.dictDetailColums)
        })
      }
      else if (type === 'refresh') {
        console.log('this.dictData==', this.dictData);
        await this.$store.dispatch('system/getAllDict')
        return;
      }
      this.dialogVisible = true;
    },
    async onDialogConfirm() {
      let isValid = false;
      console.log('onDialogConfirm--this.$refs.dialogForm.==', this.$refs.dialogForm);
      this.$refs.dialogForm.validate(valid => {
        console.log('onDialogConfirm--valid==', valid);
        isValid = valid;
      })
      console.log('onDialogConfirm--this.saving ==', this.saving, isValid);
      if (this.saving) return this.$message.error('请勿重复提交');
      if (!isValid) return this.$message.error('请检查提交内容');

      this.saving = true;
      try {
        const payload = this.$json.cloneDeep(this.dialogForm);
        console.log('onDialogConfirm--payload==', payload);
        let data = {};
        // TODO 优化
        if (this.dialogType === 'addDict') {
          const res = await systemDictAdd(payload);
          data = res.data;
        }
        else if (this.dialogType === 'addDictDetail' || this.dialogType === 'editDictDetail') {
          payload.dict_id = this.selDict.id;
          const res = await systemDictDetailEdit(payload);
          data = res.data;
        }
        else {
          return this.$message.warning('未知操作')
        }
        // console.log('subFn==', typeof(subFn));
        // const { data } = await subFn(payload);
        console.log('onDialogConfirm==', data);
        if (payload?.id && data.length) {
          if (data[0]) {
            this.$message.success(`更新成功`)
            this.dialogType === 'addDict' && this.getData();
            ['addDictDetail', 'editDictDetail'].includes(this.dialogType) && this.getDictDetail();
            this.dialogVisible = false;
          }
          else {
            this.$message.error(`异常：添加失败`)
          }
        }
        else if (data && data.length === 2) {
          if (data[1]) {
            this.dialogType === 'addDict' && this.getData();
            this.dialogType === 'addDictDetail' && this.getDictDetail();
            this.$message.success(`${payload.id ? '更新成功' : '添加成功'}`)
            this.dialogVisible = false;
          }
          else {
            this.$message.error(`添加失败: ${payload.label} ${payload.value} 已存在`)
          }
        }
        else {
          this.$message.error(`异常：操作失败`)
        }
      }
      catch (e) {
        console.log('goodsAddCate--e==', e);
      }
      this.saving = false;
    }
  }
}

</script>
<style lang="scss" scoped>
.title-box {
  font-size: 18px;
  font-weight: bold;
}
.container-box {
  padding: 20px;
  .table-wrap {
    margin-top: 40px;
    .filter-box {
      margin-bottom: 10px;
    }
    ::v-deep .table-header-row {
      color: #000;
      font-weight: bold !important;
    }
  }
}
</style>
